package com.example.eventreg.security;


import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;  // 引入 JwtUtil 类，用于处理 token 验证和解析
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的 Authorization 字段中的 token
        String token = request.getHeader("Authorization");
        System.out.println("------");
        System.out.println(request);
        System.out.println("BaseToken: "+token);
        // 判断 token 是否存在且以 "Bearer " 开头
        if (token != null) {

            if(token.startsWith("Bearer "))
            {
                token = token.substring(7);
            }
            // 去除 "Bearer " 前缀，获取纯净的 token
            // 验证 token 是否有效
            System.out.println("token: "+token);
            if (jwtUtil.isTokenValid(token)) {
                // 解析 token 获取用户名
                String username = jwtUtil.getFullNameFromToken(token);
                String userid = jwtUtil.getUserIdFromToken(token);
                System.out.println("username: "+username);
                System.out.println("userID: "+userid);
                // 创建一个身份验证对象（这里暂时不传权限信息，可以根据实际需求添加）
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, null);

                // 设置额外的用户信息（如请求来源等），可省略
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                // 将认证信息设置到 Spring Security 的 SecurityContext 中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        // 继续请求的处理
        filterChain.doFilter(request, response);
    }
}